// pages/me/house/bindHouse/bindHouse.js
const options = [];
import {
    fetchData,resultJudge
} from '../../../../utils/request'
import {
    getUserInfo
} from '../../../../utils/util'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        userId: "",
        estateName: '',
        estateList:[],
        isUpdate:false,
        HouseData:{},
        estateNames:[],
        estateIndex:-1,
        showType: false,
        houseNumber: 200,
        columns: ['个人用户', '商户', '其他'],
        buildType: -1,
        buildIndex:-1,
        buildList:['一栋','二栋','三栋','四栋','五栋','六栋','西20栋','西21栋'],
        rankList: ['业主', '租户'],
        rank:-1,
        approveList: [],
        approveId:-1,
        ApproveUserList: [],
        city: "湖北省孝感市",
        UserInfo: {},
        idCard:"",
        buildId:""
    },
    //==============修改选择框事件================
    bindPickerChange: function (e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            buildType: e.detail.value
        })
    },
    bindEstateChange: function (e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            estateIndex: e.detail.value
        })
    },
    //==============适配选择框事件================
    getApproveList() {
        let approveList = this.data.ApproveUserList.map(item => {
            return item.nickName
        })
        
        this.setData({
            approveList: approveList
        })
    },
    changeEstateList(){
        let estateNames=this.data.estateList.map(item=>{
            return item.estateName
        })
        this.setData({
            estateNames:estateNames
        })
    },
    //==============修改选择框事件================
    bindRank(e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            rank: e.detail.value
        })
    },
    bindBuildNum(e){
        console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            buildIndex: e.detail.value
        })
    },
    //==============修改选择框事件================
    bindApproveUser(e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            approveId: e.detail.value
        })
    },
    //==============获取审批人列表================
    getApproveUserList() {
        fetchData('/base/estate/getApproveUserList', "", "GET", res => {
            if (res.data.code == 200) {
                this.setData({
                    ApproveUserList: res.data.rows
                })
                this.getApproveList()
            }
        }, err => {

        })
    },
    //==============获取小区列表================
    getBuildChoice() {
        fetchData('/base/estate/list', "", "GET", res => {
            if (res.data.code == 200) {
                this.setData({
                    estateList: res.data.rows
                })
                this.changeEstateList()
            }
        }, err => {

        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let userId = options.userId
        let buildId=options.buildId
        this.getBuildChoice() //获取小区列表
        this.getApproveUserList() //获取审批人列表
        if(buildId){
            this.setData({
                buildId: buildId
            })
            this.getBuildById(buildId)
        }
        this.setData({
            userId: userId
        })
     
    },
    getBuildById(id){
        fetchData(`/base/build/${id}`,"","GET",res=>{
          let result=resultJudge(res,"data");
          this.setData({
            HouseData:result,
            isUpdate:true
          })
          this.changeData()
        })
    },
    changeData(){
        let house=this.data.HouseData
    //    let estate= this.data.estateList.filter(item=>{
    //         return item.estateId==house.estateId
    //     })[0]
    //    let estateNames= this.data.estateNames;
    //   let index=estateNames.indexOf(estate.estateName)
       let buildIndex=this.data.buildList.indexOf(house.buildNum)
       let user= this.data.ApproveUserList.filter(item=>{
           return item.userId==house.userId
       })[0]
       let approveId=this.data.approveList.indexOf(user.nickName)
       this.setData({
        buildIndex:buildIndex,
        buildType:house.buildType,
        rank:house.rank,
        idCard:house.idCard,
        approveId:approveId
       })
    },
    //==============绑定房间================
    bindHouse() {
        if (!this.data.city) {
            wx.showToast({
                title: '城市不能为空！',
                icon:"error"
            })
            return;
        }
        if (this.data.estateIndex==-1) {
            wx.showToast({
                title: '小区不能为空！',
                icon:"error"
            })
            return;
        }
        if (this.data.buildIndex==-1) {
            wx.showToast({
                title: '楼栋编号不能为空！',
                icon:"error"
            })
            return;
        }
        if (!this.data.houseNumber) {
            wx.showToast({
                title: '房间号不能为空！',
                icon:"error"
            })
            return;
        }
        if (this.data.buildType===-1) {
            wx.showToast({
                title: '类型不能为空！',
                icon:"error"
            })
            return;
        }
        if (this.data.rank===-1) {
            wx.showToast({
                title: '身份不能为空！',
                icon:"error"
            })}
            if (!this.data.idCard) {
                wx.showToast({
                    title: '身份证号不能为空！',
                    icon:"error"
                })
            return;
        }
        if (!this.data.approveId) {
            wx.showToast({
                title: '审批人不能为空！',
                icon:"error"
            })
        return;
    }
    if(!this.data.isUpdate){
        this.submitHouse()
    }else{
        this.updateHouse(this.data.buildId)
    }
    },
    getEstateId(){
        let estateName= this.data.estateNames[this.data.estateIndex]
        estateName= this.data.estateList.filter(item=>{
            return item.estateName==estateName
        })
        return estateName[0]
    },
    updateHouse(buildId){
     this.changeHouse('/base/build/updateHouse',"PUT",buildId)
    },
    submitHouse(){
      this.changeHouse("/base/build/bindHouse","POST","")
    },
    changeHouse(url,method,buildId){
        let user= this.data.ApproveUserList.filter(item=>{
            return item.nickName==this.data.approveList[this.data.approveId];
        })
        let buildDto={
            city:this.data.city,
            estateName:this.data.estateName,
            houseNumber:this.data.houseNumber,
            nickName:this.data.UserInfo.nickName,
            phone:this.data.UserInfo.phonenumber,
            buildType:this.data.buildType,
            rank:this.data.rank,
            idCard:this.data.idCard,
            estate:this.getEstateId(),
            buildNum:this.data.buildList[this.data.buildIndex],
            approveUser:{
            nickName:user[0].nickName,
            userId:user[0].userId,
            deptId:user[0].deptId
            },
            buildId:buildId    
        }
        fetchData(url,buildDto,method,res=>{
       if(res.data.code==200){
           wx.navigateBack()
       }
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        let user = getUserInfo()
        this.setData({
            UserInfo: user
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})